(function () {
  main();

  function main() {
    loadJS('https://ax.minicg.com/yepnope.min.js', ()=>{
      yepnope({
        load: [
          'https://ax.minicg.com/layui/css/layui.css',
          'https://ax.minicg.com/layui/layui.all.js',
          'https://ax.minicg.com/axlib.js',
        ],
        complete: inited
      });
    });
  }

  function inited() {
    override();
    ccpl(.8, 2500, 1000);
    
    let marker = $('.axlib-layui-nav');
    let rep = marker.parent().parent();
    let rid = rep.attr('id');
    let data = axlib.repeater.getData(rid);
    data = axlib.repeater.format(data, 1);

    let treeData = getTreeData(data);
    rep.children().hide();
    rep.css({
      // 'height': '100vh',
      'text-align': 'left',
      'background': '#393D49'
    });

    buildMenu(rep, treeData);

    layui.use('element', function(){
        var element = layui.element;
        element.render('rid', '');
    });
  }

  function buildMenu(rep, data) {
    let nid = 'nav_' + rep.attr('id');
    rep.append(getMenuRootTemplate(nid));

    let nav = $('#' + nid);

    // 构建一级菜单
    $.each(data, (i, n)=>{
      let item = getMenuItemTemplate(n);
      if (n.children.length == 0) {
        item = item.replace('<span class="layui-nav-more"></span>', '');
      }
      nav.append(item);
      if (n.children.length > 0) {
        // 插入子级菜单
        addSubMenu(n.children, nav.children('li').last());
      }
    });
  }

  function addSubMenu(children, parent) {
    $.each(children, (i, n)=>{
      let item = getMenuSubItemTemplate(n);
      if (n.children.length == 0) {
        item = item.replace('<span class="layui-nav-more"></span>', '');
      }
      parent.append(item);
      if (n.children.length > 0) {
        addSubMenu(n.children, parent.find('dd').last());
      }
    });
  }

  function getMenuLinkTemplate(data) {
    let { menu, icon, badge, page, active, frame } = data;
    let isActive = active=='this'?'layui-this':'';
    let onClickHandler = '';
    
    if (page != '') {
      let url = page.toLowerCase().split(' ').join('_') + '.html';
      if (frame != '') {
        let iframe, fid;
        iframe = $axure(`@${frame}`).$();
        if (iframe.length > 0) {
          fid = iframe.attr('id');
        }
        onClickHandler = `window.layuiNavOpenLink('${url}', '${fid}')`;
      } else {
        onClickHandler = `window.layuiNavOpenLink('${url}')`;
      }
    }

    return `
    <a href="javascript:;" lay-tips="${menu}" lay-direction="2" onclick="${onClickHandler}" class="${isActive}">
      <i class="layui-icon layui-icon-${icon}" style="display:${icon?'inline':'none'}"></i>
      <cite>${menu}</cite>
      <span class="layui-badge" style="display:${badge?'inline-block':'none'}">${badge}</span>
      <span class="layui-nav-more"></span>
    </a>
    `;
  }

  function getMenuSubItemTemplate (data) {
    let { active } = data;
    let isActive = active=='this'?'layui-this':'';
    
    return `
    <dl class="layui-nav-child">
        <dd class="layui-nav-itemed ${isActive}">
          ${getMenuLinkTemplate(data)}
        </dd>
    </dl>
    `;
  }

  function getMenuItemTemplate(data) {
    return `
    <li class="layui-nav-item layui-nav-itemed">
      ${getMenuLinkTemplate(data)}
    </li>
    `;
  }

  function getMenuRootTemplate(id) {
    return `<ul id="${id}" class="layui-nav layui-nav-tree" lay-shrink="" lay-filter="test"></ul>`;
  }

  function getTreeData(data) {
    // 子级归档
    $.each(data, (j, k)=>{
      k.children = [];
      $.each(data, (g, h)=>{
        if (h.menu == k.parent) {
          h.children.push(k);
        }
      });
    });

    // 重组数据
    let tree = [];
    $.each(data, (j,k)=>{
      if (k.parent=='/') {
        tree.push(k);
      }
    });
    return tree;
  }

  function override() {
    $axure.internal(function ($ax) {
      // 改写页面跳转方法
      var nav = $ax.public.navigate;
      window.layuiNavOpenLink = function (url, fid) {
        if (!url) return;
        if (!fid) {
          nav({url: url, target: "current", includeVariables: true, useGlobalVarNameInUrl: false});
        } else {
          nav({url: url, target: "frame", includeVariables: true, frame: $(`#${fid}_input`)});
        }
      };
      // $ax.public.navigate = $ax.navigate = function () {
      //   // {url: "page_2.html", target: "current", includeVariables: true, useGlobalVarNameInUrl: false}
      //   // {url: "page_2.html", target: "frame", includeVariables: true, frame: iframe#u0_input}
      //   console.log(...arguments);
      //   console.log(arguments[0].frame);
      //   // nav(...arguments);
      // };
    });
  }

  function ccpl(alpha, delay, dur) {
    // 加这个提示仅仅为了拉新，毕竟本人付出了劳动，也不阻止你禁用这个提示，以前做了很多免费组件，绝大部分用户都是连句谢谢都没有，当然本人也不是为了那句谢谢，只是如果能和用户发生一点互动，个人会比较开心
    $('body').append(`<div id="ccpl" style="position:absolute;width:100%;bottom:0;text-align:center;opacity:${alpha};pointer-events:none;font-size:12px;background:rgba(255,0,0,1);color:#FFF;padding:2px;">基于Layui构建的Axure无限层级菜单中继器, 制作者 wavef - 免费索取加群:883847896</div>`);
    $("#ccpl").delay(delay).animate({opacity:0},{duration:dur,complete:()=>{$("#ccpl").remove();}});
  }

  function loadJS(url, callback) {
    var s = document.createElement('script');
    s.onload = callback || function () {
      console.log(url + ' loaded.')
    };
    s.setAttribute('src', url);
    document.querySelector('head').appendChild(s);
  }
}());